#include "IniFile.h"


CIniFile::CIniFile(CString ProfileName)
{
	if (!ProfileName.IsEmpty()) {		
		if (_tcsstr(ProfileName.GetBuffer(), TEXT("\\"))) {//full path
			m_IniFilePath = ProfileName;
		} else {	//relative path
			TCHAR szAppPath[BUFSIZ];
			GetModuleFileName(NULL, szAppPath, MAX_PATH);
			TCHAR *pSlice = _tcsrchr(szAppPath, '\\');
			*(pSlice+1) = 0;	//slice the path
			_tcscat_s(szAppPath, BUFSIZ, ProfileName.GetBuffer());
			m_IniFilePath.SetString(szAppPath);
		}
		FileExist(m_IniFilePath);
	}	
}


CIniFile::~CIniFile(void)
{
	m_IniFilePath = TEXT("");
}

BOOL CIniFile::Open(CString m_pszIniFileName)
{
	FileExist(m_pszIniFileName);
	m_IniFilePath = m_pszIniFileName;
	return TRUE;
}
BOOL CIniFile::Close()
{
	m_IniFilePath = TEXT("");
	return TRUE;
}
CString CIniFile::GetProfileString(LPCTSTR lpszSection, LPCTSTR lpszEntry, LPCTSTR lpszDefault /* = NULL */)
{
	CString strRet(lpszDefault);
	if (!FileExist(m_IniFilePath)) {
		return strRet;
	}
	TCHAR szEntry[BUFSIZ];
	GetPrivateProfileString(lpszSection, lpszEntry, lpszDefault, szEntry, BUFSIZ, m_IniFilePath.GetBuffer());
	strRet.SetString(szEntry);
	return strRet;
}
UINT CIniFile::GetProfileInt(LPCTSTR lpszSection, LPCTSTR lpszEntry, int nDefault /* = 0 */)
{
	if (!FileExist(m_IniFilePath)) {
		return nDefault;
	}
	return GetPrivateProfileInt(lpszSection, lpszEntry, nDefault, m_IniFilePath.GetBuffer());
}

BOOL CIniFile::WriteProfileString(LPCTSTR lpszSection, LPCTSTR lpszEntry, LPCTSTR lpszValue)
{ 
	if (lpszSection == NULL||lpszEntry==NULL) {
		return FALSE;
	}
	if (FileExist(m_IniFilePath)) {
		return WritePrivateProfileString(lpszSection, lpszEntry, lpszValue, m_IniFilePath);
	}
	return FALSE;
}
BOOL CIniFile::WriteProfileInt(LPCTSTR lpszSection, LPCTSTR lpszEntry, int nValue)
{
	if (lpszSection == NULL||lpszEntry==NULL) {
		return FALSE;
	}
	TCHAR szNumStr[64];
	if (FileExist(m_IniFilePath)) {
		return WritePrivateProfileString(lpszSection, lpszEntry, _itot(nValue, szNumStr, 10), m_IniFilePath);
	}
	return FALSE;		
}
BOOL CIniFile::FileExist(CString FilePath)
{
	BOOL bOk = TRUE;
	if (FilePath.IsEmpty()) {
		return FALSE;
	}
	if (!PathFileExists(FilePath.GetBuffer())) {
		HANDLE hFile = CreateFile(FilePath.GetBuffer(),
			GENERIC_WRITE|GENERIC_READ, FILE_SHARE_READ, NULL,
			CREATE_NEW, FILE_ATTRIBUTE_NORMAL, NULL);
		if (hFile != INVALID_HANDLE_VALUE) {
			CloseHandle(hFile);
		} else {
			MessageBox(NULL, TEXT("Create Profile error\n"), NULL, MB_OK);
			bOk = FALSE;
		}
	}
	return bOk;
}